package com.hxc.orangeyule;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.widget.Toast;

import com.hxc.orangeyule.callback.DataCallBack;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * Created by Administrator on 2016/3/14.
 */
public abstract class MyFragmentActivity extends FragmentActivity {
    private HttpUtils mHttpUtils;
    private HttpHandler mHttpHandler;
    private Dialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        initData();
        setData();
        setListener();
    }

    private void init() {
        mHttpUtils = new HttpUtils();
        mDialog = new ProgressDialog(this);
        mDialog.setTitle(R.string.load);
        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (mHttpHandler != null) {
                    mHttpHandler.cancel();
                }
            }
        });
    }

    protected abstract void setListener();

    protected abstract void setData();

    protected abstract void initView();

    protected abstract void initData();

    protected void getRequset(String path, final DataCallBack callBack) {

        mHttpHandler = mHttpUtils.send(HttpRequest.HttpMethod.GET, path, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                mDialog.show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mDialog.cancel();
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    callBack.onSuccessed(responseInfo.result);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                mDialog.cancel();
                Toast.makeText(MyFragmentActivity.this, R.string.net_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled() {
                super.onCancelled();
                mDialog.cancel();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHttpHandler != null) {
            mHttpHandler.cancel();
        }
    }
}
